package com.service

import android.R
import android.annotation.SuppressLint
import android.app.*
import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.widget.ImageView
import com.baidu.location.demo.MainActivity
import com.fragment.GpsFragment.ScreenId
import com.fragment.GpsFragment.mediaProjectionManager
import com.microsoft.signalr.HubConnectionState
import com.service.HubService.hubConnection
import com.util.util
import io.reactivex.subjects.ReplaySubject
import java.io.ByteArrayOutputStream

class ScreenService : Service() {

    var width:Int?=null
    var height:Int?=null
    var dpi:Int?=null
    var stream : ReplaySubject<ByteArray>?=null
    var imageReader: ImageReader?=null
    var mediaProjection: MediaProjection?=null
    override fun onStart(intent: Intent?, startId: Int) {
        super.onStart(intent, startId)
    }
    override fun onCreate() {
        super.onCreate()

    }
    @SuppressLint("NewApi")
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
            createNotificationChannel()
        }
        var mResultCode = intent?.getIntExtra("code", -1);
        dpi=intent?.getIntExtra("dpi",0)
        width=intent?.getIntExtra("width",0)
        height=intent?.getIntExtra("height",0)
        var mResultData = intent?.getParcelableExtra<Intent>("data");
        mediaProjection=mediaProjectionManager?.getMediaProjection(mResultCode!!,mResultData!!)
        ScreenData()
        return super.onStartCommand(intent, flags, startId)
    }
    @SuppressLint("WrongConstant", "NewApi")
    private fun ScreenData(){
        imageReader= ImageReader.newInstance(width!!, height!!, PixelFormat.RGBA_8888,2)
        mediaProjection?.createVirtualDisplay("screen_shot",width!!,height!!,dpi!!,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC, imageReader!!.surface,null,null)
        imageReader!!.setOnImageAvailableListener({
            readerImages(it)
        },null)
    }
    private fun createNotificationChannel() {
        val builder: Notification.Builder = Notification.Builder(this.applicationContext) //获取一个Notification构造器
        val nfIntent = Intent(this, MainActivity::class.java) //点击后跳转的界面，可以设置跳转数据
        builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    this.resources,
                    R.drawable.alert_light_frame
                )
            ) // 设置下拉列表中的图标(大图标)
            .setContentTitle("屏幕共享") // 设置下拉列表里的标题
            .setSmallIcon(R.drawable.alert_light_frame) // 设置状态栏内的小图标
            .setContentText("共享屏幕中") // 设置上下文内容
            .setWhen(System.currentTimeMillis()) // 设置该通知发生的时间

        /*以下是对Android 8.0的适配*/
        //普通notification适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId("notification_id")
        }
        //前台服务notification适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            val channel = NotificationChannel(
                "notification_id",
                "notification_name",
                NotificationManager.IMPORTANCE_LOW
            )
            notificationManager.createNotificationChannel(channel)
        }
        val notification: Notification = builder.build() // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND //设置为默认的声音
        startForeground(110, notification)
    }
    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    private fun readerImages(reader: ImageReader){
        val images=reader.acquireNextImage()
        var pixelStride=images.planes[0].pixelStride;
        var rowStride=images.planes[0].rowStride;
        var rowPadding=rowStride-pixelStride*images.width
        val bitmap= Bitmap.createBitmap(images.width+rowPadding / pixelStride, images.height, Bitmap.Config.ARGB_8888)
        bitmap.copyPixelsFromBuffer(images.planes[0].buffer)
        var t= Thread{
            if(hubConnection!=null&&hubConnection?.connectionState== HubConnectionState.CONNECTED){
                if(stream==null){
                    stream= ReplaySubject.create()
                    Log.d("", "接收人id$ScreenId")
                    hubConnection?.send("UploadStream",stream,ScreenId)
                }
                var baos = ByteArrayOutputStream()
                bitmap.compress(Bitmap.CompressFormat.JPEG,5,baos)
                bitmap.recycle()
                if(baos.size()>0)stream?.onNext(util.zip(baos.toByteArray())!!)
            }else if(hubConnection!=null){
                hubConnection?.start()
            }
        };
        t.start()
        images.close()
    }
}